package com.itheima.arrayListTest;

import java.util.ArrayList;

/**
 * @Author 王加鑫
 * @Date 2021/4/29 11:47
 * @Version 1.0
 * 循环遍历删除集合中的元素
 */
public class RemoveTest {

    public static void main(String[] args) {
        for1();
        for2();

    }

    /*
    正着循环遍历删除
     */
    public static void for1(){
        String s1 = "傻逼";
        String s2 = "SB";
        String s3 = "TMD";
        String s4 = "傻逼";
        ArrayList<String> list = new ArrayList<>();
        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);

        for (int i = 0; i < list.size(); i++) {
            if("傻逼".equals(list.get(i))){
                list.remove(i);
                i--;
            }
        }

        System.out.println(list);
    }

    /*
    反着遍历删除
     */
    public static void for2(){
        String s1 = "傻逼";
        String s2 = "SB";
        String s3 = "TMD";
        String s4 = "傻逼";
        ArrayList<String> list = new ArrayList<>();
        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);

        for (int i = list.size()-1; i >= 0; i--) {
            if("傻逼".equals(list.get(i))){
                list.remove(i);
            }

        }
        System.out.println(list);
    }
}
